//
//  XMLComposeViewController.swift
//  Weibo
//
//  Created by mac on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class XMLComposeViewController: UIViewController,UITextViewDelegate {

    private lazy var rightButton :UIButton = {
        let button = UIButton()
        button.frame.size = CGSize(width: 45, height: 30)
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        
        
        return button
        
    }()
    private lazy var titleView :UILabel = {
    
        let lable = UILabel(textColor: UIColor.lightGrayColor(), fontSize: 17)
        
        if let name = XMLUserAcountViewModel.sharedUserAcountViewModel.userAcount?.name {
        
            let title = "发微博\n\(name)"
            let range = (title as NSString).rangeOfString(name)
            let attributedStr = NSMutableAttributedString(string: title)
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: range)
            lable.attributedText = attributedStr
        }else {
        
            lable.text = "发微博"
        }
        lable.numberOfLines = 0
        lable.sizeToFit()
        lable.textAlignment = .Center
       
        
        return lable
    }()
    
    private lazy var composeTextView :XMLComposeTextView = {
    
        let view = XMLComposeTextView()
        view.font = UIFont.systemFontOfSize(16)
        view.alwaysBounceVertical = true
        return view
    }()
    
    private lazy var composeToolBar :XMLComposeToolBar = {
    
        let toolBar = XMLComposeToolBar(frame: CGRectZero)
        
        return toolBar
    }()
    
    private lazy var composePicView :XMLComposePictureView = {
    
        let view = XMLComposePictureView()
        
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        //监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    @objc private func keyboardChange(notification :NSNotification) {
    
        let keyboardFrame = (notification.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        let animationDuration = (notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]! as! NSNumber).doubleValue
        
        composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - view.frame.size.height)
        }
        UIView.animateWithDuration(animationDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        composeTextView.delegate = self
        composeTextView.placeHolder = "请输入内容"
        setupNavUI()
        view.addSubview(composeTextView)
        view.addSubview(composeToolBar)
        composeTextView.addSubview(composePicView)
        
        
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(composeToolBar.snp_top)
        }
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        composePicView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(composeTextView).offset(100)
            make.centerX.equalTo(composeTextView)
            make.width.equalTo(composeTextView).offset(-20)
            make.height.equalTo(composeTextView.snp_width).offset(-20)
        }
        
        
        composeToolBar.didSelectedButtonClosure = { [weak self] (buttonType: XMLComposeToolBarButtonType) in
        
            switch buttonType {
            
            case .Picture:
                print("picture")
                self!.selectePic()
            case .Mention:
                print("Mention")
            case .Trend:
                print("Trend")
            case .Emoticon:
                print("Emoticon")
            case .Add:
                print("Add")
            }
        }
    }
    
    private func setupNavUI() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", font: 15, target: self, action: "cancleAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }
    
    
    @objc private func cancleAction() {
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func sendAction() {
    
        print("send")
        let accessToken = XMLUserAcountViewModel.sharedUserAcountViewModel.accessToken!
        let status = composeTextView.text!
        
        XMLNetWorkTools.sharedTools.sendWeiBoMessage(accessToken, status: status) { (response, error) -> () in
            
            SVProgressHUD.show()
            if error != nil {
            
                SVProgressHUD.showErrorWithStatus("发送失败")
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
            SVProgressHUD.dismissWithDelay(3)
            self.dismissViewControllerAnimated(true, completion: nil)
            
        }
    }
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        
    }
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}


extension XMLComposeViewController :UINavigationControllerDelegate,UIImagePickerControllerDelegate {
    
    func selectePic() {
        print("选择图片")
        let imagePickerVC = UIImagePickerController()
        imagePickerVC.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
        
            imagePickerVC.sourceType = .Camera
        }else {
        
            imagePickerVC.sourceType = .PhotoLibrary
        }
        
        // 判断前置摄像头是否可用
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("前置摄像头可用")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("后置摄像头可用")
        } else {
            print("摄像头不可用")
        }
        
        imagePickerVC.allowsEditing = true
        
        presentViewController(imagePickerVC, animated: true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        composePicView.addImage(image)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
